import React, { Suspense, useEffect, useMemo } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import useRouterActions from '@/store/actions/router';
import routes from './routes';
import { useChannelOrigin } from '@/common/hooks';
import { getRequestUrlParams } from '@/common/utils';
// 路由控制
const RouterCtrl = ({ config, route }) => {
  const routerActions = useRouterActions();
  const { component, redirect, meta, name } = config;
  // const { isIos } = usePlatform();
  const [channel] = useChannelOrigin();
  const { location: { search } = {} } = route;
  useEffect(() => {
    routerActions.setMeta(meta);
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  }, []);

  return useMemo(() => {
    const isDownload = name === 'Download';
    // if (isIos && isDownload) {
    //   window.location.href = 'https://m.xinqiuzhibo.com/';
    //   return;
    // }
    if (redirect) {
      const isRedirect = !search.includes('channelCode') && channel?.name === 'channelCode' && channel?.value;
      const { agentId } = getRequestUrlParams(global.location.href);
      if (isDownload && isRedirect) {
        let url = `${redirect}?${channel.name}=${channel.value}`;
        if (agentId) {
          url += `&agentId=${agentId}`;
        }
        return (<Redirect to={url} />);
      }
      if (!isDownload) {
        // 重定向
        return (<Redirect to={redirect} />);
      }
    }
    // 正常渲染页面组件
    return React.createElement(component, route);
  }, [config]);
};

// 路由
const Router = () => (
  <Suspense fallback={null}>
    <Switch>
      {routes.map((row, index) => (
        <Route
          render={(props) => (<RouterCtrl config={row} route={props} />)}
          path={row.path}
          strict={row.strict}
          exact={row.exact}
          key={row.name || index}
        />
      ))}
    </Switch>
  </Suspense>
);

export default Router;
